package com.dangf.app.launcher.activity

import android.os.Handler
import android.support.v7.app.AlertDialog
import android.view.View
import com.dangf.app.launcher.R
import com.dangf.app.launcher.app.BaseActivity
import com.dangf.app.launcher.app.HaisApp
import com.dangf.app.launcher.app.V
import com.dangf.app.launcher.dao.MainDao
import com.dangf.app.launcher.entity.Machine
import com.dangf.app.launcher.model.BaseModel
import com.dangf.app.launcher.model.MachineModel
import com.yanzhenjie.nohttp.rest.Response
import kotlinx.android.synthetic.main.activity_machine_register.*
import pw.hais.utils_lib.http.OnHttpListener
import pw.hais.utils_lib.utils.L
import pw.hais.utils_lib.utils.MachineInfoUtils
import pw.hais.utils_lib.utils.ShellUtils

/**
 * 注册机器
 * Created by 管理员 on 2017/9/12.
 */
class MachineRegisterActivity : BaseActivity(R.layout.activity_machine_register), View.OnClickListener, OnHttpListener<MachineModel> {

    override fun onInitViewsAndData() {
        btn_register.setOnClickListener(this)
        btn_close.setOnClickListener(this)

        edit_store_name.setText(V.mStore?.name)
        edit_machine_code.setText(HaisApp.MachineCode)
        edit_machine_type.setText(MachineInfoUtils.productType)
        edit_system_info.setText(MachineInfoUtils.systemVersion)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btn_register -> {
                val machineName = edit_machine_name.text.toString()
                val machineProduct = edit_machine_type.text.toString()
                val machineCode = edit_machine_code.text.toString()
                val machineSystem = edit_system_info.text.toString()
                val machine = Machine()
                machine.name = machineName
                machine.code = machineCode
                machine.product = machineProduct
                machine.version = machineSystem
                if (machineName.isEmpty() || machineProduct.isEmpty() || machineCode.isEmpty() || machineSystem.isEmpty()) L.showShort("请输入完整的注册信息！")
                else MainDao.registerMachineInfo(machine, this@MachineRegisterActivity)
            }
            R.id.btn_close -> {
                AlertDialog.Builder(this).setTitle("警告").setMessage("您是否要放弃注册,关闭手机?").setNegativeButton("取消", null)
                        .setPositiveButton("关机", { _, _ -> ShellUtils.execCmd("reboot -p", true) }).show()
            }
        }
    }

    override fun onSuccess(what: Int, response: Response<MachineModel>?, data: MachineModel) {
        if (data.status == 100) {
            L.showShort("注册成功,手机重启中...")
            Handler().postDelayed({ ShellUtils.execCmd("reboot", true) }, 2000)
        }
    }

}